package com.qingyun.customview.bezier

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.View
import android.view.animation.LinearInterpolator

class SimpleBezierView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : View(context, attrs, defStyleAttr) {
    private val mScreenWidth: Int
    private val mScreenHeight: Int
    private val amplitude = 100f.dp2px()//振幅
    private val mPath = Path()
    private val mPaint = Paint().apply {
        color = Color.BLUE
        style = Paint.Style.FILL
        isAntiAlias = true
        isDither = true
    }
    private var mOffset = 0


    init {
        mScreenWidth = getScreenWidth()
        mScreenHeight = getScreenHeight()
        startAnimator()
    }

    private fun startAnimator() {
        ValueAnimator.ofInt(0, mScreenWidth).apply {
            duration = 1000
            repeatMode = ValueAnimator.RESTART
            repeatCount = ValueAnimator.INFINITE
            interpolator = LinearInterpolator()
            addUpdateListener {
                mOffset = it.animatedValue as Int
                invalidate()
            }
        }.also {
            it.start()
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
    }

    override fun onDraw(canvas: Canvas) {
        mPath.reset()

        val screenWidth = mScreenWidth.toFloat()
        val screenHeight = mScreenHeight.toFloat()
        mPath.moveTo(-screenWidth, screenHeight / 2)

        mPath.quadTo(
            (-screenWidth * 3 / 4) + mOffset,
            (screenHeight / 2) - amplitude,
            (-screenWidth / 2) + mOffset,
            screenHeight / 2
        )
        mPath.quadTo(
            (-screenWidth / 4) + mOffset,
            (screenHeight / 2) + amplitude,
            0f + mOffset,
            screenHeight / 2
        )
        mPath.quadTo(
            (screenWidth / 4) + mOffset,
            (screenHeight / 2) - amplitude,
            (screenWidth / 2) + mOffset,
            screenHeight / 2
        )
        mPath.quadTo(
            (screenWidth * 3 / 4) + mOffset,
            (screenHeight / 2) + amplitude,
            screenWidth + mOffset,
            screenHeight / 2
        )

        mPath.lineTo(screenWidth, screenHeight)
        mPath.lineTo(0f, screenHeight)
        canvas.drawPath(mPath, mPaint)

    }

    //dp转px
    private fun Float.dp2px(): Float {
        return this * resources.displayMetrics.density
    }

    //获取屏幕宽度
    private fun getScreenWidth(): Int {
        return resources.displayMetrics.widthPixels
    }

    //获取屏幕高度
    private fun getScreenHeight(): Int {
        return resources.displayMetrics.heightPixels
    }
}